<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线聊天和传文件</title>
    <link href="../css/bootstrap5.3.min.css" rel="stylesheet" type="text/css" />
    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/vue.min.js"></script>
    <script src="../js/axios.min.js"></script>
    <script>
        let global_URL = ''; 
    </script>
</head>

<body>
    <div id="wechart" class="container">
        <!--        header 头部导航栏-->
        <div id="my_header"> </div>
        <!-- <div>
            操作反馈：{{mess}}
        </div> -->

        <!-- 聊天的页面 -->
        <div id="chart_div" class="col-sm-9 col-lg-7">
            <h4 class="bg-success pb-3 pt-3">
                welcome, name=【{{name}}】,
                uid= <span class="label label-primary">{{uid}}</span>
            </h4>
            <!-- 发送窗口 -->
            <div id="send_div" class="border border-info">
                <h2 class="bg-default">消息发送界面</h2>
                <form @submit.prevent="send">
                    <div class="mb-1 row">
                        <label class="col-4 col-form-label" for="send_to_name">对方用户名:</label>
                        <div class="col-8">
                            <input class="form-control col-sm-10" type="text" id="send_to_name" v-model="send_to_name"
                                required>
                        </div>

                    </div>
                    <div class="mb-1">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" v-model="send_type_file"  id="checkbox_select_file">
                            <label class="form-check-label" for="checkbox_select_file">是否发送文件：{{ send_type_file }}</label>
                        </div>
                    </div>

                    <div v-if="!send_type_file" class="mb-2 ">
                        <div>
                            <label for="send_mess">发送的文本:</label>
                        </div>
                        <textarea class="form-control" type="text" id="send_mess" v-model="send_mess" rows="4"
                            cols="40"></textarea>
                    </div>
                    <div v-else class="mb-2 ">
                        <label for="attach_file">发送的附件:</label>
                        <input class="form-control" type="file" name="attach_file" id="attach_file"
                            @change="handleFileChange">
                    </div>
                    <div class="row">
                        <div class="col-3"></div>
                        <div class="col-4">
                            <button type="submit" type="button" class="btn btn-success">发送</button>
                        </div>
                    </div>
                </form>
            </div>
            <!-- 最新消息 -->
            <div>---------------------------------------</div>
            <h2 class="bg-default">消息接受界面</h2>
            <div>
                <button type="button" class="btn btn-info" @click="query_all">获取最新消息</button>
            </div>
            <div id="show_mess_box"  class="border border-info">
                <div v-if="all_mess.length==0">
                    <h4>暂时无消息</h4>
                </div>
                <div v-for="(item,idx) in all_mess" :key="idx">
                    <div>fromUID: {{item.fromUID}}, name:{{item.fromName}}, type={{item.type}} :</div>
                    <!-- 文本信息 -->
                    <div v-if="item.type=='txt'">
                        <textarea class="form-control" type="text" v-model="item.data" rows="2" cols="40"
                            readonly></textarea>
                    </div>
                    <!-- 文件信息 -->
                    <div v-else>
                        <a target="_blank" :href="item.data">点击下载-{{item.data}}</a>
                        <div v-if="item.type=='vid'">
                            <video :src="item.data" controls width="320px" height="256px"></video>
                        </div>
                    </div>
                    <div>---------------------------------------</div>
                </div>
            </div>
        </div>

    </div>
</body>

<script src="../js/jquery-3.6.0.min.js"></script>
<script>
    $(function () {
        $("#my_header").load("../index_header.html");
    });
    function showmess(mess) {
        var div = $("<div class=mymess>" + mess + "</div>");
        $("body").append(div);

        var intv = setInterval(() => {
            let top = div.css("top");
            top = parseInt(top.split("px")[0]);
            if (top > 500) {
                div.remove();
                clearInterval(intv);
            }
            div.css("top", (top + 5) + "px");
            div.css("opacity", 1 - (top / (800.0)));
        }, 17);
    }

    const MyRedAX = axios.create({
        maxRedirects: 0
    });

    var app = new Vue({
        el: "#wechart",
        data() {
            return {
                count: 1, // 定时器
                save_pwd: false, //是否保存密码
                uid: '',
                name: "",
                pwd: '',
                mess: '这是消息窗口',
                api_addr: global_URL, // 后端的接口端点，需要修改
                send_to_name: '',
                send_mess: '',
                fileData: null,
                send_type_file: false,
                all_mess: []
            };
        },
        methods: {
            get_my_info() {
                MyRedAX.get(this.api_addr + "get_my_info")
                    .then(response => {
                        // 请求成功处理
                        console.log(response.data);
                        if (response.data.res == "Y") {
                            showmess("你已经登录");
                            this.name = response.data.name;
                            this.uid = response.data.uid;
                            // 启动定时器
                            /*
                            this.timer = setInterval(() => {
                                this.count--;
                                if(this.count == 0){
                                    this.count = 3;
                                    this.query_all(); // 查询最新消息
                                }
                            }, 1000); // 每隔1000毫秒（1秒）执行一次
                            */
                            // 获取最新消息
                            this.query_all();
                        } else {
                            showmess("你未登录");
                        }
                    })
                    .catch(error => {
                        // 请求失败处理
                        alert("catch error");
                        console.error(error);
                    });
            },
            handleFileChange(event) {
                const file = event.target.files[0];
                this.fileData = file;
            },
            send() {
                // 使用axios发送 
                // 创建FormData对象  
                const formData = new FormData();
                formData.append('file', this.fileData); // 'file'是文件字段名，file是要发送的文件对象
                formData.append('fromUID', this.uid);
                formData.append('toName', this.send_to_name);
                formData.append("data", this.send_mess);

                let url = "send1"; //发送文本
                if (this.send_type_file) { //发送文件
                    if (this.fileData == null) {
                        alert("文件不能为空");
                        return;
                    }
                    url = "send2"
                }

                showmess("准备发送...");
                MyRedAX.post(this.api_addr + url, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data' // 设置请求头为multipart/form-data  
                    }
                })
                    .then(response => {
                        // 请求成功处理  
                        console.log(response.data);

                        if (response.data == "succ") {
                            showmess("发送成功");
                        } else {
                            showmess("发送失败");
                        }
                    })
                    .catch(error => {
                        // 请求失败处理  
                        alert("catch error");
                        console.error(error);
                    });
            },
            query_all() {
                // 使用axios发送GET请求  
                MyRedAX.get(this.api_addr + "query_my_mess", {
                    params: {
                        'uid': this.uid
                    } // 将数据作为查询参数发送
                }).then(response => {
                    console.log(response.status)
                    // 请求成功处理  
                    // console.log(response.data); 
                    if (response.data.res == "succ") {
                        this.all_mess = response.data.arr.reverse();
                    } else {
                        alert("错误，无法获取最新数据，尝试刷新");
                        console.error(response.data);
                    }
                })
                    .catch(error => {
                        // 请求失败处理  
                        alert("catch error");
                        console.error(error);
                    });
            }
        },
        mounted() {
            // 保存： wechart_user wechart_pwd 
            this.get_my_info();

            // <!-- SSE推送 -->
            var sseSource = new EventSource("./userConnect");
            sseSource.onmessage = (event) => {
                // console.log("test=>", event.data ); 
                let KKK = JSON.parse(event.data);
                this.all_mess = KKK.arr.reverse();

            }

        },
        beforeDestroy() {
            // 销毁定时器  
            /*
            if (this.timer) {  
                clearInterval(this.timer);  
                this.timer = null;  
            }  */
        }
    });
</script>
<style>
    .mymess {
        left: 100px;
        top: 50px;
        position: fixed;
        border: 1px solid #e9c5c5;
        border-radius: 5px;
        text-align: center;
        padding: 10px;
        width: 350px;
        font-size: large;
        color: aliceblue;
        background-color: #000000;
        opacity: 1;
    }
</style>

</html>